var app = getApp();
var URL = app.globalData.URL;

Page({
  data: {

    orderSn:"",
    billList:'',

  },
  onLoad(options) {
    console.log(options.orderSn); 
    var orderSn = options.orderSn;
    this.setData({orderSn:orderSn});

    my.request({
      url: `${URL}/app-api/chl/bill/listAllByOrderSn`,
      data: {orderSn:this.data.orderSn},
      success: (res) => {
        console.log(res.data);
        this.setData({billList:res.data.data});
      },
      fail: (err) => {
        console.log(err);
      }
    });
  },
  tqhk(event) {
    var bill = event.currentTarget.dataset.bill;
    console.log("传递的bill为：" + JSON.stringify(bill));
    my.confirm({
      title: '提前还款',
      content: '若想提前还款点击确定，否则点击取消！',
      confirmColor: '',
      success: (result) => {
        console.log(result.confirm);
        if(result.confirm){
          this.kszf(bill);
        }else{
          my.alert({content:'已取消提前还款'});
        }
      },
      fail: (err) => {
      },
      complete: () => {
        
      }
    });
    
  },
  kszf(bill){
    //创建订单
    my.request({
      url: `${URL}/app-api/chl/app/alipayTradeCreate`,
        data: {
          total_amount: bill.jine,
          out_trade_no: bill.billSn,
          sjid: bill.sjid,
          scene: 'bar_code',
          subject: '订单'+bill.orderSn+',第'+bill.qc+'期提前还款',
          buyer_id: app.globalData.user_id
        },
        headers:{"tenant-id":"1"},
      success: (result) => {
          var tradeNo;
          if(result.data.success){
            tradeNo = result.data.tradeNo;
            console.log("发起支付");
            console.log(result);
            //发起支付
            my.tradePay({
               tradeNO: tradeNo,
            success: (result) => {
              console.log("支付成功");
              console.log(result);
              if (result.resultCode=="9000") {
                my.alert({content:'支付成功！'});
                //更改bill
                // bill.id;
                // bill.tqTradeNo;
                // bill.billStatus;
                //更改userPay

                my.request({
                  url: `${URL}/app-api/chl/bill/updateBillById`,
                  method: '',
                  data: {
                    id:bill.id,
                    tqTradeNo:tradeNo,
                    billStatus:'已还款',
                  },
                  success: (result) => {
                    console.log("更新订单成功");
                  },
                  fail: () => {
                    
                  }
                });

              }else{
                my.alert({content:'支付失败！'});
              }
            },
            fail: (err) => {
              console.log("失败2");
              my.alert({content:'支付失败！'});
             }
            });
          }
      },
      fail: (err) => {
        console.log(err);
        my.alert({content:'支付失败！'});
      }
    });
  }
});
